<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <div style="display:flex;justify-content:space-between;">
        <div style="width: 40%">
          <el-form-item label="考试名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="考试名称" clearable />
          </el-form-item>
          <el-form-item label="组织机构" prop="institutional">
            <el-input
              :disabled="dataForm.state"
              v-model="dataForm.institutional"
              placeholder="组织机构"
              clearable
            />
          </el-form-item>
          <el-form-item label="考试分类" prop="cateId">
            <el-select
              style="width:100%"
              v-model="dataForm.cateId"
              :disabled="dataForm.state"
              placeholder="点击选择分类"
              clearable
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="考试地点" prop="place">
            <el-input type="text" v-model="dataForm.place" placeholder="考试地点" clearable />
          </el-form-item>
<!--          <el-form-item label="考试描述" prop="brief">-->
<!--            <el-input-->
<!--              :disabled="dataForm.state"-->
<!--              v-model="dataForm.brief"-->
<!--              placeholder="考试简介说明"-->
<!--              clearable-->
<!--            />-->
<!--          </el-form-item>-->
        </div>
        <div style="width: 50%">
          <el-form-item label="考试类型" prop="type">
            <el-radio-group v-model="dataForm.type" @change="Changes">
              <el-radio :disabled="dataForm.state" :label="1">正式考试</el-radio>
              <el-radio :disabled="dataForm.state" :label="2">模拟考试</el-radio>
              <el-radio :disabled="dataForm.state" :label="3">三违考试</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="考试时长" prop="duration">
            <el-input
              type="number"
              v-model="dataForm.duration"
              placeholder="考试时长"
              @keyup.native="value"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="及格分数" prop="passMark">
            <el-input
              type="number"
              v-model="dataForm.passMark"
              placeholder="及格分数"
              @keyup.native="value"
              clearable
            >
              <template slot="append">分</template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="dataForm.type == 2" label="模拟次数" prop="number">
            <el-input-number v-model="dataForm.number" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="试卷" prop="paperId">
            <el-button :disabled="dataForm.state" type="text" @click="handlerOpenPaperDialog">选择试卷</el-button>
            <el-input v-model="dataForm.paperName" placeholder="试卷名称" disabled />
          </el-form-item>
        </div>
      </div>
      <el-form-item label="考试时间" prop="timeRange">
        <el-date-picker
          v-model="dataForm.timeRange"
          type="datetimerange"
          :disabled="dataForm.state"
          value-format="timestamp"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item label="参与人员" prop="trainType">
        <el-radio-group v-if="dataForm.type != 3" v-model="dataForm.examType" @change="typeChange">
          <el-radio :disabled="dataForm.state" :label="0">全员参加</el-radio>
          <el-radio :disabled="dataForm.state" :label="1">按部门参与</el-radio>
          <el-radio :disabled="dataForm.state" :label="2">按人员参与</el-radio>
        </el-radio-group>
        <el-button
          v-if="dataForm.examType == 2 || dataForm.type == 3"
          typeof="primary"
          :disabled="dataForm.state"
          style="margin-left: 20px"
          @click="handlerOpenUserDialog"
        >选择参与人员</el-button>
      </el-form-item>
      <el-form-item prop="deptIds" v-if="dataForm.examType == 1">
        <el-cascader
          :options="deptList"
          clearable
          placeholder="请选择参与部门"
          v-model="dataForm.deptIds"
          :props="deptListTreeProps"
          filterable
        />
      </el-form-item>
      <el-form-item prop="userList" v-if="dataForm.examType == 2 || dataForm.type == 3">
        <el-table :data="dataForm.userList" max-height="300">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column property="realname" label="姓名" width="200" />
          <el-table-column property="deptName" label="部门" />
          <el-table-column property="gender" label="性别">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.gender==1">男</el-tag>
              <el-tag v-else>女</el-tag>
            </template>
          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="dataForm.state"
                @click="deleteHandle(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
    </div>

    <el-dialog title="试卷列表" :visible.sync="dialogPaperVisible" append-to-body>
      <el-form :inline="true" :model="dataForm">
        <el-form-item>
          <el-input v-model="dataForm.keyWorld" placeholder="请输入考试名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button @click="getPaperList(dataForm.keyword)">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="paperList">
        <el-table-column property="id" label="id" width="150" />
        <el-table-column property="paperName" label="试卷名称" width="200" />
        <el-table-column property="cateName" label="试卷分类" />
        <el-table-column header-align="center" align="center" width="150" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handlerSelectPager(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-size="pageSize"
        :disabled="dataForm.state"
        :total="totalCount"
        layout="total, prev, pager, next"
      />
    </el-dialog>

    <el-dialog title="人员列表" :visible.sync="dialogUserVisible" append-to-body>
      <el-form :inline="true" :model="userListForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input
            v-model="userListForm.realname"
            placeholder="请输入姓名"
            clearable
            @clear="getUserList()"
            style="width: 160px;"
          />
          <el-cascader
            :options="deptList"
            :props="deptListTreeProp"
            v-model="userListForm.deptId"
            clearable
            filterable
            @clear="getUserList()"
            placeholder="请选择参与部门"
          />
          <el-input
            v-model="userListForm.identityCard"
            placeholder="请输入身份证号"
            clearable
            @clear="getUserList()"
            style="width: 160px;"
          />
          <!--<el-input v-model="userListForm.mobile" placeholder="请输入手机号码" clearable @clear="getUserList()" style="width: 160px;"></el-input>-->
        </el-form-item>
        <el-form-item>
          <el-button @click="getUserList()">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="userList"
        v-loading="dataListLoading"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
        max-height="500"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column property="realname" label="姓名" width="200" />
        <el-table-column property="deptName" label="部门" />
        <el-table-column property="gender" label="性别">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.gender==1">男</el-tag>
            <el-tag v-else>女</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentUserChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        :pager-count="5"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 10px"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectUserSubmit" :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from '@/utils'

export default {
  data() {
    return {
      visible: false,
      dialogUserVisible: false,
      dialogPaperVisible: false,
      dataListLoading: false,
      loading: false,
      selectUserList: [],
      paperList: [],
      cateList: [],
      userList: [],
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      multipleSelection: [],
      excludeIds: [],
      deptList: [],
      deptListTreeProps: {
        multiple: true,
        expandTrigger: 'hover',
        label: 'name',
        value: 'id',
        children: 'children',
        emitPath: false
      },
      deptListTreeProp: {
        checkStrictly: true,
        expandTrigger: 'hover',
        label: 'name',
        value: 'id',
        children: 'children',
        emitPath: false
      },
      deptId: '',
      deptsList: [],
      dataForm: {
        keyWorld: '',
        institutional: '',
        state: false,
        realname: '',
        id: 0,
        trainId: 30,
        name: '',
        examType: 0,
        timeRange: [],
        userList: [],
        cateId: '',
        duration: '',
        passMark: '',
        paperId: '',
        brief: '',
        type: 1,
        place: '',
        paperName: '',
        deptIds: '',
        deptName: '',
        deptId: ''
      },
      dataRule: {
        name: [
          { required: true, message: '考试名称不能为空', trigger: 'blur' }
        ],
        cateId: [
          { required: true, message: '考试分类id不能为空', trigger: 'blur' }
        ],
        timeRange: [
          { required: true, message: '考试时间不能为空', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '考试时长不能为空', trigger: 'blur' }
        ],
        passMark: [
          { required: true, message: '及格分数不能为空', trigger: 'blur' }
        ],
        paperId: [
          { required: true, message: '试卷id不能为空', trigger: 'blur' }
        ],
        // brief: [
        //   {required: true, message: '考试简介说明不能为空', trigger: 'blur'}
        // ],
        institutional: [
          { required: true, message: '组织机构不能为空', trigger: 'blur' }
        ]
      },
      userListForm: {
        realname: '',
        deptId: '',
        identityCard: '',
        mobile: ''
      }
    }
  },
  methods: {
    getCateList() {
      this.$http({
        url: this.$http.adornUrl(`/exam-admin/exam/cate/select`),
        method: 'post'
      }).then(res => {
        this.cateList = res.data
      })
    },
    Changes(val) {
      if (val === 3) {
        this.dataForm.examType = 2
      }
    },
    value() {
      // eslint-disable-next-line
      this.dataForm.duration = this.dataForm.duration.replace(/[^\.\d]/g, '')
      this.dataForm.duration = this.dataForm.duration.replace('.', '')
    },
    getDeptList() {
      this.$http({
        url: this.$http.adornUrl('/usercenter-admin/dept/select'),
        method: 'post'
      }).then(data => {
        this.deptList = treeDataTranslate(data.data, 'id')
      })
    },
    init(id, status) {
      this.excludeIds = []
      this.deptList = []
      this.userList = []
      this.dataForm.userList = []
      this.dataForm.deptIds = []
      this.getCateList()
      this.getDeptList()
      this.dataForm.state = !!status
      this.dataForm.id = id || 0
      this.visible = true
      this.userListForm = {
        realname: '',
        deptId: '',
        identityCard: '',
        mobile: ''
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm.paperName = ''
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/exam-admin/exam/info/${this.dataForm.id}`
            ),
            method: 'post'
          }).then(data => {
            if (data && data.code === 200) {
              this.dataForm.name = data.data.name
              this.dataForm.id = data.data.id
              this.dataForm.cateId = data.data.cateId
              this.dataForm.duration = data.data.duration
              this.dataForm.passMark = data.data.passMark
              this.dataForm.paperId = data.data.paperId
              this.dataForm.brief = data.data.brief
              this.dataForm.type = data.data.type
              this.dataForm.paperName = data.data.paperName
              this.dataForm.timeRange = [data.data.stime, data.data.etime]
              this.dataForm.examType = Number(data.data.publisherType)
              this.dataForm.userList = data.data.users
              this.excludeIds = data.data.userIds
              this.dataForm.deptIds = JSON.parse(data.data.deptIdJson)
              this.dataForm.place = data.data.place
              this.dataForm.institutional = data.data.institutional
            }
          })
        }
      })
    },

    // 改变培训类型
    typeChange() {
      this.dataForm.userList = []
      // this.dataForm.deptIds = []
    },
    getUserList() {
      this.dataListLoading = true
      // eslint-disable-next-line eqeqeq
      this.$http({
        url:
          this.dataForm.type === 3
            ? this.$http.adornUrl('/user/endorsements/getEndorsementsUsers')
            : this.$http.adornUrl('/usercenter-admin/user/list'),
        method: 'post',
        data: {
          realname: this.userListForm.realname,
          identityCard: this.userListForm.identityCard,
          deptId: this.userListForm.deptId,
          mobile: this.userListForm.mobile,
          page:
            this.userListForm.realname ||
            this.userListForm.identityCard ||
            this.userListForm.deptId ||
            this.userListForm.mobile
              ? ''
              : this.pageIndex,
          limit: this.pageSize
        }
      })
        .then(res => {
          this.dataListLoading = false
          this.userList = res.data.list
          this.totalCount = res.data.totalCount
          this.selectUserList[this.pageIndex - 1] = this.dataForm.userList
            .map(x => this.userList.filter(i => i.userId === x.userId))
            .map(x => x[0])
          this.selectUserList[this.pageIndex - 1].forEach(row =>
            this.$refs.multipleTable.toggleRowSelection(row, true)
          )
        })
        .catch(() => {
          this.dataListLoading = false
        })
    },

    selectUserSubmit() {
      this.dataForm.userList = []
      this.selectUserList.forEach(item => {
        item.forEach(childItem => {
          this.dataForm.userList.push(childItem)
        })
      })
      this.dialogUserVisible = false
    },

    // 删除选中用户
    deleteHandle(index) {
      this.dataForm.userList.splice(index, 1)
    },

    // 表单提交
    dataFormSubmit() {
      this.loading = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          let sTime = this.dataForm.timeRange[0]
          let eTime = this.dataForm.timeRange[1]
          let userIds = []
          let endorsemetIds = []
          if (this.dataForm.userList) {
            this.dataForm.userList.forEach(item => {
              userIds.push(item.userId)
              endorsemetIds.push(item.id)
            })
          }
          console.log(this.dataForm.timeRange[0])
          // let deptIds = []
          // if (this.dataForm.deptIds && this.dataForm.deptIds.length > 0) {
          //   for (let i = 0; i < this.dataForm.deptIds.length; i++) {
          //     if (this.dataForm.deptIds[i] && this.dataForm.deptIds[i].length > 0) {
          //       deptIds.push(this.dataForm.deptIds[i][this.dataForm.deptIds[i].length - 1])
          //     }
          //   }
          // }
          this.$http({
            url: this.$http.adornUrl(
              `/exam-admin/exam/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: {
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              cateId: this.dataForm.cateId,
              duration: this.dataForm.duration,
              passMark: this.dataForm.passMark,
              startTime: sTime,
              endTime: eTime,
              paperId: this.dataForm.paperId,
              brief: this.dataForm.brief,
              deptIdJson: JSON.stringify(this.dataForm.deptIds),
              userIds: userIds,
              endorsemetIds: endorsemetIds,
              deptIds: this.dataForm.deptIds,
              examType: this.dataForm.examType,
              type: this.dataForm.type,
              place: this.dataForm.place,
              institutional: this.dataForm.institutional
            }
          })
            .then(data => {
              console.log(sTime)
              if (data && data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.loading = false
                this.visible = false
                this.$emit('refreshDataList')
              } else {
                this.$message.error(data.msg)
              }
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    handlerSelectPager(row) {
      this.dataForm.paperId = row.id
      this.dataForm.paperName = row.paperName
      this.dialogPaperVisible = false
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getPaperList()
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.getUserList()
    },
    // 选择人员列表当前页
    currentUserChangeHandle(val) {
      this.pageIndex = val
      this.getUserList()
    },

    getPaperList(keyword) {
      this.$http({
        url: this.$http.adornUrl('/exam-admin/paper/list'),
        method: 'post',
        data: {
          keyword: this.dataForm.keyWorld,
          page: this.dataForm.keyWorld ? '' : this.pageIndex,
          limit: this.pageSize
        }
      }).then(data => {
        if (data && data.code === 200) {
          this.paperList = data.data.list
          this.totalCount = data.data.totalCount
        } else {
          this.paperList = []
          this.totalCount = 0
        }
        this.dataListLoading = false
      })
    },
    handlerOpenPaperDialog() {
      this.dialogPaperVisible = true
      this.pageIndex = 1
      this.pageSize = 20
      this.totalCount = 0
      this.getPaperList()
    },
    handlerOpenUserDialog() {
      this.dialogUserVisible = true
      this.pageIndex = 1
      this.pageSize = 20
      this.totalCount = 0
      this.userListForm = {
        realname: '',
        deptId: '',
        identityCard: '',
        mobile: ''
      }
      this.getUserList()
    },
    // 多选用户
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.selectUserList[this.pageIndex - 1] = val
    }
  }
}
</script>
